<template>
	<view class="user-login">
		<view class="user-info">
			<view class="avatar">
				<open-data type="userAvatarUrl"></open-data>
			</view>

			<view class="nick-name">
				<open-data type="userNickName"></open-data>
			</view>

		</view>

		<!-- <button v-show="!userInfo" open-type="getUserInfo" @getuserinfo="getUserInfo" class="login-btn">获取用户信息</button> -->
		<!-- #ifdef MP-WEIXIN -->
		<button v-show="!userInfo" @click="getUserInfo" class="login-btn">获取用户信息</button>
		<button v-show="userInfo" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="login-btn">登录</button>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<button v-show="!userInfo" type="primary" @click="appWxRegister" class="login-btn">微信登录</button>
		<!-- #endif -->
		<button  @click="cancelLogin" class="cancel-btn">取消登录</button>


	</view>

</template>

<script>
	const appInstance = getApp();
	import common from '../../../static/js/common'
	export default {
		data() {
			return {
				userInfo: null
			}
		},
		onLoad: function(options) {
			
			appInstance.globalData.getCustomer(res => {

				if (res.data.telephone) {
					// uni.switchTab({
					uni.navigateTo({
						url: '/sm_shop/pages/home/home'
					});
				}

			});
		},
		methods: {

			getPhoneNumber: function(e) {

				// console.log(e);
				console.log(e.detail.errMsg);
				// console.log(e.detail.iv);
				// console.log(e.detail.encryptedData);

				if (e.detail.errMsg == 'getPhoneNumber:ok') {

					var t = this;
					var url = '&r=member.xcx.register';
					var data = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData,
						session_key: uni.getStorageSync('session_key'),
						userInfo: this.userInfo
					};

					// todo 查看是否有推荐人
					var referee = uni.getStorageSync('referee');
					if( referee ){
						data.referee = referee;
					} 
					appInstance.globalData.request(url, data, "POST", res => {

						console.log(res);
						if (!res.data.status) {
							uni.switchTab({
							// uni.navigateTo({
								url: '/sm_shop/pages/home/home'
							});
						} else {

							var desc = res.data.description ? res.data.description : '登录异常';
							uni.showToast({
								title: desc,
								icon: 'none',
								duration: 800
							});

						}

					});

				}



			},

			getUserInfo: function(e) {

				var t = this;
				wx.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						
						// console.log( res )
						if (res.errMsg == 'getUserProfile:ok') {
						
							t.userInfo = res.rawData;
						
						}
					}
				})
				

			},
			
			/**
			 * app应用获取微信用户信息
			 */
			appWxRegister: function() {
				
				appInstance.globalData.app_register()
			},
			
			cancelLogin:function(){
				uni.navigateBack({
					
				})
			}
		}
	}
</script>

<style lang="less">
	@import './login.less';
</style>
